package edu.ynu.se.xiecheng.achitectureclass.config;

import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.DeviceType;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.service.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class DataInitializer implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private GreenhouseDao greenhouseDao;

    @Autowired
    private DeviceDao deviceDao;

    private final DeviceService deviceService;

    @Autowired
    public DataInitializer(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Override
    @Transactional
    public void run(ApplicationArguments args) throws Exception {
        try {
            logger.info("Starting data initialization...");
            initializeData();
            logger.info("Data initialization completed successfully.");
        } catch (Exception e) {
            logger.error("Data initialization failed: " + e.getMessage(), e);
        }
    }

    private void initializeData() {
        // 检查是否已经初始化
        if (greenhouseDao.count() > 0) {
            logger.info("Data already initialized, skipping...");
            return;
        }

        logger.info("Creating greenhouse...");
        // 1. 创建大棚
        Greenhouse greenhouse = new Greenhouse();
        greenhouse.setName("智能大棚1号");
        greenhouse.setAddress("云南大学呈贡校区");
        greenhouse.setArea(new BigDecimal("1000.00"));
        greenhouse = greenhouseDao.save(greenhouse);
        logger.info("Greenhouse created with ID: {}", greenhouse.getId());

        logger.info("Creating devices...");
        // 2. 创建设备
        createDevices(greenhouse);
        logger.info("Devices created successfully.");
    }

    private void createDevices(Greenhouse greenhouse) {
        // 使用实际的传感器ID
        createDevice("空气温度检测器", DeviceType.AIR_TEMPERATURE.getDeviceSerial(), 
                DeviceType.AIR_TEMPERATURE, "℃", null, greenhouse);
        createDevice("空气湿度检测器", DeviceType.AIR_HUMIDITY.getDeviceSerial(), 
                DeviceType.AIR_HUMIDITY, "%", null, greenhouse);
        createDevice("土壤温度检测器", DeviceType.SOIL_TEMPERATURE.getDeviceSerial(), 
                DeviceType.SOIL_TEMPERATURE, "℃", null, greenhouse);
        createDevice("土壤PH检测器", DeviceType.SOIL_PH.getDeviceSerial(), 
                DeviceType.SOIL_PH, "pH", null, greenhouse);
        createDevice("二氧化碳检测器", DeviceType.CO2.getDeviceSerial(), 
                DeviceType.CO2, "ppm", null, greenhouse);

        // 只保留一个摄像头
        createDevice("监控摄像头", "AB9831171", DeviceType.CAMERA, null, 
                "ezopen://open.ys7.com/AB9831171/1.hd.live", greenhouse);
    }

    private void createDevice(String name, String serial, DeviceType type, String unit, 
                            String monitorUrl, Greenhouse greenhouse) {
        try {
            // 检查设备是否已存在
            if (deviceDao.findById(serial).isPresent()) {
                logger.info("Device with serial {} already exists, skipping...", serial);
                return;
            }

            // 1. 先创建设备
            Device device = new Device();
            device.setName(name);
            device.setDeviceSerial(serial);
            device.setDeviceType(type);
            device.setUnit(unit);
            device.setMonitorUrl(monitorUrl);
            
            // 2. 保存设备
            device = deviceDao.save(device);
            logger.info("Device created with serial: {}", device.getDeviceSerial());
            
            // 3. 绑定设备到大棚
            try {
                device = deviceService.bindDeviceToGreenhouse(device.getDeviceSerial(), greenhouse.getId());
                logger.info("Device bound to greenhouse: {}", device.getDeviceSerial());
            } catch (Exception e) {
                logger.error("Failed to bind device to greenhouse: {} - {}", serial, e.getMessage());
                // 绑定失败不影响设备创建
            }
            
        } catch (Exception e) {
            logger.error("Failed to create device: {} - {}", serial, e.getMessage());
        }
    }
} 